package com.cooksys.film_rental.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.cooksys.film_rental.dao.FilmCategoryDao;
import com.cooksys.film_rental.model.Category;
import com.cooksys.film_rental.model.Film;
import com.cooksys.film_rental.model.FilmCategory;
import com.cooksys.film_rental.model.FilmCategoryId;

@Repository("FilmCategoryDao")
@Transactional
public class FilmCategoryDaoImpl implements FilmCategoryDao {

	@Autowired(required = true)
	private SessionFactory sessionFactory;

	/**
	 * 
	 * @return the current session from the internal {@link SessionFactory}
	 */
	public Session currentSession() {
		return sessionFactory.getCurrentSession();
	}

	@Override
	public FilmCategory getFilmCategoryByFilmCategoryId(
			FilmCategoryId filmCategoryId) {
		Session session = currentSession();

		// returns a record from the FILM_CATEGORY table as a FilmCategory
		// object based on the given filmCategoryId, the table's primary key
		String hql = "from FilmCategory f where f.id = :filmCategoryId";
		Query query = session.createQuery(hql);
		query.setEntity("filmCategoryId", filmCategoryId);

		return (FilmCategory) query.list().get(0);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<FilmCategory> searchFilmCategoriesByFilm(Film film) {
		Session session = currentSession();

		// returns records from the FILM_CATEGORY table as a FilmCategory
		// object based on the given film
		String hql = "from FilmCategory f where f.film = :film";
		Query query = session.createQuery(hql);
		query.setEntity("film", film);

		return query.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<FilmCategory> searchFilmCategoriesByCategory(Category category) {
		Session session = currentSession();

		// returns records from the FILM_CATEGORY table as a FilmCategory
		// object based on the given category
		String hql = "from FilmCategory f where f.category = :category";
		Query query = session.createQuery(hql);
		query.setEntity("category", category);

		return query.list();
	}

}
